package com.hz.Tech2Real.yeyouwang.web;

import javax.servlet.http.HttpServlet;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class YanzhengmaServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
                this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	
	
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		// 向页面输出图片
		response.setContentType("image/jpeg");

		/**
		 * 用java代码生成一张图片
		 * 
		 */
		// 2.在内存中产生一个图像 BufferedImage

		// 设置图片的长和高
		int width = 130;//
		int height = 30;

		BufferedImage bImage = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		// 3.得到一个画笔
		Graphics g = bImage.getGraphics();

		// 4.画一个矩形框
		g.setColor(Color.BLUE);
		g.drawRect(0, 0, width, height);

		// 5.填充矩形框的背景颜色、
		g.setColor(Color.yellow);
		g.fillRect(0, 0, width, height);

		// 6.画随机干扰线
		Random random = new Random();// 随机数类

		g.setColor(Color.GRAY);
		for (int i = 0; i < 20; i++) {
			g.drawLine(random.nextInt(width), random.nextInt(height),
					random.nextInt(width), random.nextInt(height));
		}

		// 7.画字符串
		g.setColor(Color.RED);
		g.setFont(new Font("黑体", Font.BOLD | Font.ITALIC, 20));// 设置字体

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < 4; i++) {
			String str = "";
			int a = random.nextInt(9);// 随机生成 随机数
			g.drawString(str + a, 30*i+5,a+20);// 往图片上写 数字
			// 保存随机生成的随机数
			sb.append(a);
		}
		// 把StringBuffer 保存在 session中
		request.getSession().setAttribute("core", sb.toString());

		// 8.输出给客户端
		ImageIO.write(bImage, "jpg", response.getOutputStream());
	}

}
